Skip to content

Latest commit

 

History

History
37 lines (31 loc) · 955 Bytes

09. DST and ZST.org

File metadata and controls

37 lines (31 loc) · 955 Bytes

DST

rules

  • we cannot know how long a DST is until runtime
  • we cannot create a variable of type DST
  • we cannot take an argument of type DST

Golden Rule: we must always put values of dynamically sized types behind a pointer of some kind

examples of dst

  • [T]
  • str (str is a DST, while &str is slice)
  • trait object

size_of_val VS size_of::<&DST>

use std::fmt::Display;
use std::mem::{size_of, size_of_val};

fn main() {
    assert!(vec![
        &1i8 as &dyn Display,
        &2i64 as &dyn Display,
        &3i128 as &dyn Display,
    ]
    .into_iter()
    .map(|x| size_of_val(x))  // 这里 x 是 &T, size_of_val 的参数是 &T, 所以计算的是 T 的大小
    .eq([1, 8, 16]));

    let a = &1i8 as &dyn ToString;
    assert!(16, size_of_val(&a));
    assert!(1, size_of_val(a));
    assert_eq!(size_of::<&u8>() * 2, size_of::<&dyn Display>());
}

ZST

https://runrust.miraheze.org/wiki/Zero-sized_type